<template>
	<!-- 模板内容保持不变 -->
	<div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
		<!-- 背景装饰 -->
		<div class="fixed inset-0 overflow-hidden pointer-events-none">
			<div
				class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob">
			</div>
			<div
				class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000">
			</div>
			<div
				class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000">
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="container mx-auto px-12 py-10 pt-32 relative z-10">
			<!-- 顶部：返回与标题 -->
			<div class="flex items-center justify-between mb-10">
				<div class="flex items-center gap-4">
					<el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
						<el-icon class="mr-2 text-xl">
							<ArrowLeft />
						</el-icon>
						返回班级列表
					</el-button>
					<h1 class="text-4xl font-bold text-gray-900">{{ classInfo?.className || '班级详情' }}</h1>
				</div>
				<div class="flex items-center gap-4">
					<el-button type="danger" @click="dissolveClass" class="rounded-full px-6">
						解散班级
					</el-button>
					<div class="text-lg text-gray-600 font-medium">{{ currentWeekRange }}</div>
				</div>
			</div>

			<!-- 主体布局 -->
			<div class="grid grid-cols-1 lg:grid-cols-3 gap-10">
				<!-- 左侧：班级信息 -->
				<div class="lg:col-span-1">
					<div
						class="bg-white rounded-3xl shadow-xl border border-gray-200 p-8 sticky top-32 h-full min-h-[calc(100vh-8rem)] flex flex-col relative">
						<!-- 班级头像和基本信息 -->
						<div class="p-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl mb-8">
							<div class="flex items-center gap-6">
								<div
									class="w-28 h-28 bg-white bg-opacity-20 rounded-2xl flex items-center justify-center shadow-lg">
									<span
										class="text-white text-6xl font-bold select-none leading-none">{{ getFirstChar(classInfo?.className) }}</span>
								</div>
								<div class="text-white">
									<h2 class="text-3xl font-bold mb-3">{{ classInfo?.className }}</h2>
									<p class="text-blue-100 text-lg">{{ classInfo?.grade }}</p>
								</div>
							</div>
						</div>

						<!-- 班级详细信息 -->
						<div class="space-y-8 pb-28">
							<!-- 基本信息 -->
							<div class="space-y-6">
								<div class="flex items-center gap-5">
									<div class="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center">
										<el-icon class="text-blue-600 text-2xl">
											<User />
										</el-icon>
									</div>
									<div>
										<p class="text-lg text-gray-500 mb-2">班主任</p>
										<p class="text-xl font-semibold text-gray-900">
											{{ classInfo?.teacherName || '陈老师' }}
										</p>
									</div>
								</div>
								<div class="flex items-center gap-5">
									<div class="w-16 h-16 bg-green-100 rounded-xl flex items-center justify-center">
										<el-icon class="text-green-600 text-2xl">
											<UserFilled />
										</el-icon>
									</div>
									<div>
										<p class="text-lg text-gray-500 mb-2">班级人数</p>
										<p class="text-xl font-semibold text-gray-900">
											{{ classInfo?.studentCount || 0 }}人
										</p>
									</div>
								</div>
							</div>

							<!-- 班级统计 -->
							<div class="pt-8 border-t border-gray-200">
								<h4 class="text-xl font-semibold text-gray-700 mb-6">班级统计</h4>
								<div class="grid grid-cols-2 gap-6">
									<div
										class="bg-blue-50 rounded-2xl p-6 text-center h-24 flex flex-col justify-center">
										<div class="text-3xl font-bold text-blue-600">{{ classInfo?.studentCount || 0 }}
										</div>
										<div class="text-base text-blue-500">总人数</div>
									</div>
									<div
										class="bg-green-50 rounded-2xl p-6 text-center h-24 flex flex-col justify-center">
										<div class="text-3xl font-bold text-green-600">{{ courseCount }}</div>
										<div class="text-base text-green-500">课程数</div>
									</div>
								</div>
							</div>

							<!-- 班级描述 -->
							<div class="pt-8 border-t border-gray-200">
								<h4 class="text-xl font-semibold text-gray-700 mb-4">班级描述</h4>
								<p class="text-gray-700 leading-relaxed text-lg">
									{{ classInfo?.description || '该班级暂无描述。' }}
								</p>
							</div>

							<!-- 螺旋向上的动态图 -->
							<div class="mt-6 flex justify-center">
								<div class="helix-container">
									<div class="helix-row" v-for="n in 10" :key="n" :style="{ '--i': n }">
										<span class="helix-dot left"></span>
										<span class="helix-dot right"></span>
									</div>
								</div>
							</div>

							<div class="flex-1"></div>

							<!-- 快捷操作 -->
							<div class="absolute bottom-8 left-8 right-8 pt-6 border-t border-gray-200">
								<h4 class="text-xl font-semibold text-gray-700 mb-6">快捷操作</h4>
								<div class="space-y-4">
									<button @click="goToStudy"
										class="w-full h-16 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-medium text-lg rounded-2xl flex items-center justify-center gap-3 transition-all shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]">
										<el-icon class="text-2xl">
											<Reading />
										</el-icon>
										开始学习
									</button>
									<button @click="goToResources"
										class="w-full h-16 bg-gradient-to-r from-gray-500 to-gray-600 hover:from-gray-600 hover:to-gray-700 text-white font-medium text-lg rounded-2xl flex items-center justify-center gap-3 transition-all shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]">
										<el-icon class="text-2xl">
											<Files />
										</el-icon>
										查看资源
									</button>
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 右侧：课程安排与任务 -->
				<div class="lg:col-span-2 space-y-8">
					<!-- 课程安排 -->
					<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
						<div class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-4">
									<div
										class="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center">
										<el-icon class="text-white text-2xl">
											<Calendar />
										</el-icon>
									</div>
									<div>
										<h3 class="text-3xl font-bold text-gray-900 mb-2">课程安排</h3>
										<p class="text-blue-600 font-medium text-xl">{{ currentWeekRange }}</p>
									</div>
								</div>
								<div class="flex items-center gap-3">
									<el-button type="primary" size="large" :disabled="currentWeek <= 1"
										@click="prevWeek" class="rounded-full px-6 hover:shadow-md transition-shadow">
										<el-icon class="mr-2">
											<ArrowLeft />
										</el-icon>上一周
									</el-button>
									<div class="bg-white px-6 py-3 rounded-full shadow-sm border border-blue-200">
										<span class="text-lg text-blue-600 font-semibold">第{{ currentWeek }}周</span>
									</div>
									<el-button type="primary" size="large" @click="nextWeek"
										class="rounded-full px-6 hover:shadow-md transition-shadow">
										下一周<el-icon class="ml-2">
											<ArrowRight />
										</el-icon>
									</el-button>
								</div>
							</div>
						</div>

						<div class="p-8 overflow-x-auto">
							<!-- 课程表 -->
							<div class="grid grid-cols-1 lg:grid-cols-6 gap-6">
								<div v-for="(schedule, index) in weeklySchedule" :key="index" class="lg:col-span-1">
									<div
										class="bg-gradient-to-br from-white to-gray-50 rounded-3xl p-6 shadow-lg border border-gray-200">
										<div class="text-center mb-4">
											<h3 class="text-xl font-bold text-gray-800">{{ schedule.weekday }}</h3>
										</div>
										<!-- 上午 -->
										<div v-if="schedule.morning"
											class="mb-4 p-4 bg-blue-50 rounded-2xl border border-blue-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-blue-500 rounded-full"></div>
												<span class="text-sm font-medium text-blue-700">上午</span>
											</div>
											<div class="text-base font-bold text-gray-900 mb-1">
												{{ schedule.morning.course }}
											</div>
											<div class="text-xs text-gray-600 mb-2">{{ schedule.morning.courseType }} ·
												{{ schedule.morning.lecturer }}
											</div>
										</div>
										<div v-else class="mb-4 p-4 bg-gray-50 rounded-2xl border border-gray-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-gray-400 rounded-full"></div>
												<span class="text-sm font-medium text-gray-600">上午</span>
											</div>
											<div class="text-center py-2 text-gray-500">无课程安排</div>
										</div>

										<!-- 下午 -->
										<div v-if="schedule.afternoon"
											class="p-4 bg-green-50 rounded-2xl border border-green-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-green-500 rounded-full"></div>
												<span class="text-sm font-medium text-green-700">下午</span>
											</div>
											<div class="text-base font-bold text-gray-900 mb-1">
												{{ schedule.afternoon.course }}
											</div>
											<div class="text-xs text-gray-600 mb-2">{{ schedule.afternoon.courseType }}
												· {{ schedule.afternoon.lecturer }}
											</div>
										</div>
										<div v-else class="p-4 bg-gray-50 rounded-2xl border border-gray-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-gray-400 rounded-full"></div>
												<span class="text-sm font-medium text-gray-600">下午</span>
											</div>
											<div class="text-center py-2 text-gray-500">无课程安排</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<!-- 课程任务 -->
					<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
						<div
							class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-green-50 to-emerald-50 flex items-center gap-4">
							<div
								class="w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-600 rounded-2xl flex items-center justify-center">
								<el-icon class="text-white text-2xl">
									<List />
								</el-icon>
							</div>
							<div>
								<h3 class="text-3xl font-bold text-gray-900">今日任务</h3>
								<p class="text-green-600 text-xl">系统时间: {{ currentTime }}</p>
							</div>
						</div>
						<div class="p-8">
							<div class="grid grid-cols-2 md:grid-cols-3 gap-8">
								<div v-for="task in courseTasks" :key="task.id" @click="handleTask(task)"
									class="group flex flex-col items-center p-8 border-2 border-gray-100 rounded-2xl hover:border-indigo-300 hover:bg-indigo-50 transition-all duration-300 cursor-pointer transform hover:scale-105 active:scale-95">
									<div
										class="w-20 h-20 bg-gradient-to-br from-indigo-400 to-purple-500 rounded-2xl flex items-center justify-center mb-4 group-hover:shadow-lg transition-shadow">
										<el-icon class="text-white text-3xl">
											<component :is="task.icon" />
										</el-icon>
									</div>
									<span
										class="text-lg text-gray-700 font-medium group-hover:text-indigo-600 transition-colors">{{ task.name }}</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		computed,
		ref,
		onMounted,
		watch,
		reactive,
		toRefs,
		getCurrentInstance,
		markRaw
	} from 'vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ElMessage,
		ElLoading,
		ElForm,
		ElFormItem,
		ElInput,
		ElSelect,
		ElOption,
		ElTimePicker,
		ElDatePicker,
		ElDialog,
		ElButton,
		ElMessageBox
	} from 'element-plus'
	import {
		ArrowLeft,
		ArrowRight,
		Reading,
		Files,
		VideoPlay,
		Notebook,
		Document,
		User,
		UserFilled,
		Calendar,
		List,
		Plus,
		Edit
	} from '@element-plus/icons-vue'
	import axios from 'axios'
	import { setStudentIds, setStudentNames } from '@/utils/auth'
	import { userAPI } from '@/api/user'

	// 创建axios实例，指向后端Teacher服务的API
	const api = axios.create({
		baseURL: 'http://localhost:8088/api', // 显示课程表后端接口
		timeout: 5000
	})

	// 创建课程管理API实例（9002端口）
	const courseApi = axios.create({
		baseURL: 'http://localhost:9002', // 课程编辑和新建接口
		timeout: 5000
	})

	// 创建班级管理API实例（8088端口，无/api前缀）
	const classApi = axios.create({
		baseURL: 'http://localhost:8088', // 班级管理接口 - 与用户提供的最新URL端口匹配
		timeout: 5000
	})

	const route = useRoute()
	const router = useRouter()
	const {
		proxy
	} = getCurrentInstance()

	// 课程表单相关
	const dialogVisible = ref(false)
	const isEditMode = ref(false)
	const courseFormRef = ref(null)

	// 表单数据
	const courseForm = reactive({
		id: null,
		times: '',
		classTimeOn: '',
		classTimeEnd: '',
		classId: '',
		course: '',
		lecturer: '',
		dateDay: '',
		date: '',
		classRoom: ''
	})


	// 模拟班级数据
	const mockClassList = [{
			id: 1,
			className: '一年级一班',
			grade: '一年级',
			teacherName: '张老师',
			studentCount: 35,
			description: '这是一个充满活力的一年级班级，学生们积极向上，热爱学习。',
			classCode: '186749'
		},
		{
			id: 2,
			className: '三年级二班',
			grade: '三年级',
			teacherName: '李老师',
			studentCount: 32,
			description: '三年级二班是一个团结友爱的集体，同学们互相帮助，共同进步。',
			classCode: '186750'
		},
		{
			id: 3,
			className: '五年级三班',
			grade: '五年级',
			teacherName: '王老师',
			studentCount: 28,
			description: '五年级三班的学生们勤奋好学，在各项活动中表现优异。',
			classCode: '186751'
		}
	]

	const classId = computed(() => Number(route.params.id))
	const classInfo = computed(() => mockClassList.find(c => c.id === classId.value))

	// 课程相关数据
	const curriculumList = ref([]) // 确保初始化为数组
	const courseCount = ref(0)

	const getFirstChar = (text) => {
		if (!text) return '班'
		return text.trim().charAt(0).toUpperCase()
	}

	const goBack = () => router.back()
	const goToStudy = () => router.push('/study')
	const goToResources = () => router.push('/resources')

	const courseTasks = ref([{
			id: 1,
			name: '开启直播',
			icon: markRaw(VideoPlay)
		},
		{
			id: 2,
			name: '发布作业',
			icon: markRaw(Notebook)
		},
		{
			id: 3,
			name: '知识点',
			icon: markRaw(Reading)
		},
		{
			id: 4,
			name: '公告栏',
			icon: markRaw(Files)
		},
		{
			id: 5,
			name: '作业评价',
			icon: markRaw(Document)
		},
		{
			id: 6,
			name: '发布视频',
			icon: markRaw(VideoPlay)
		}
	])

	const handleTask = (task) => {
		switch (task.name) {
			case '开启直播':
				router.push(`/LiveManagement?classCode=${classId.value}`)
				break
			case '发布作业':
				router.push(`/class/${classId.value}/homework`)
				break
			case '知识点':
				router.push(`/class/${classId.value}/knowledgepoints`)
				break
			case '公告栏':
				router.push(`/class/${classId.value}/announcements`)
				break
			case '作业评价':
				router.push(`/class/${classId.value}/homework/grade`)
				break
			case '发布视频':
				router.push(`/class/${classId.value}/videos`)
				break
		}
	}

	const currentTime = ref('')
	const currentWeek = ref(1)
	const currentWeekOffset = ref(0)

	const formatDate = (d) => {
		const y = d.getFullYear()
		const m = String(d.getMonth() + 1).padStart(2, '0')
		const day = String(d.getDate()).padStart(2, '0')
		return `${y}-${m}-${day}`
	}

	const getWeekRange = (offset) => {
		const now = new Date()
		const day = now.getDay() || 7
		const monday = new Date(now)
		monday.setDate(now.getDate() - day + 1 + offset * 7)
		const sunday = new Date(monday)
		sunday.setDate(monday.getDate() + 6)
		return `${formatDate(monday)} ~ ${formatDate(sunday)}`
	}

	const currentWeekRange = computed(() => getWeekRange(currentWeekOffset.value))

	// 从数据库数据构建课程表
	const buildWeeklySchedule = () => {
		// 包含星期六
		const weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
		// 按星期几初始化课程表结构
		const schedule = weekdays.map((weekday, index) => ({
			id: weekday,
			weekday,
			morning: null,
			afternoon: null
		}));
	
		// 填充数据库课程数据
		curriculumList.value.forEach(item => {
			// 找到对应星期几的位置 (weekday 1-6 对应索引 0-5)
			const dayIndex = item.weekday - 1;
			if (dayIndex < 0 || dayIndex >= 6) return;
	
			// 构建课程信息
			const courseInfo = {
				id: item.id,
				course: item.courseName,
				// 移除理论课/实战课的判断逻辑
				courseType: '', 
				room: '', // 新表中没有教室字段
				time: item.timePeriod === 1 ? '上午' : '下午',
				lecturer: item.teacherName,
				timePeriod: item.timePeriod,
				weekday: item.weekday
			};
	
			// 填充上午/下午课程
			if (item.timePeriod === 1) {
				schedule[dayIndex].morning = courseInfo;
			} else if (item.timePeriod === 2) {
				schedule[dayIndex].afternoon = courseInfo;
			}
		});
	
		return schedule;
	};

	const weeklySchedule = computed(() => buildWeeklySchedule())

	const prevWeek = () => {
		currentWeekOffset.value -= 1
		currentWeek.value = Math.max(1, currentWeek.value - 1)
	}

	const nextWeek = () => {
		currentWeekOffset.value += 1
		currentWeek.value = currentWeek.value + 1
	}

	const updateTime = () => {
		currentTime.value = new Date().toLocaleString('zh-CN')
	}

	// 刷新学生列表到sessionStorage
	const refreshStudentList = async () => {
		try {
			console.log('开始刷新学生列表...')
			console.log('当前班级ID:', classId.value)
			
			// 直接使用当前班级的classCode获取学生列表
			const classCode = classId.value
			if (!classCode) {
				console.log('没有找到班级代码')
				return
			}
			
			const studentListResponse = await userAPI.getStudentList(classCode)
			console.log('API返回的学生列表数据:', studentListResponse)
			
			// 检查返回的数据格式
			let studentList = []
			if (studentListResponse && studentListResponse.code === 200 && Array.isArray(studentListResponse.data)) {
				studentList = studentListResponse.data
			} else if (Array.isArray(studentListResponse)) {
				// 如果直接返回数组
				studentList = studentListResponse
			} else {
				console.log('获取学生列表失败或数据格式不正确:', studentListResponse)
				return
			}
			
			if (studentList.length > 0) {
				// 提取学生ID和姓名
				const studentIds = studentList.map(student => student.studentId || student.id || student.userId)
				const studentNames = studentList.map(student => student.realName || student.username || student.name || student.nickName)
				
				// 更新sessionStorage中的学生信息
				setStudentIds(studentIds, false) // false表示只存储到sessionStorage
				setStudentNames(studentNames, false)
				
				console.log('学生列表已刷新到sessionStorage:', {
					studentIds: studentIds,
					studentNames: studentNames
				})
			} else {
				console.log('学生列表为空')
			}
		} catch (error) {
			console.error('刷新学生列表失败:', error)
			// 不显示错误提示，避免影响用户体验
		}
	}

	// 解散班级函数
	const dissolveClass = async () => {
		// 显示确认对话框
		const confirm = await ElMessageBox.confirm(
			'确定要解散这个班级吗？此操作不可撤销！',
			'确认解散班级', {
				confirmButtonText: '确定解散',
				cancelButtonText: '取消',
				type: 'warning',
				dangerouslyUseHTMLString: true
			}
		)

		if (confirm) {
			const loading = ElLoading.service({
				lock: true,
				text: '正在处理解散班级请求...',
				background: 'rgba(255, 255, 255, 0.7)'
			})

			try {
				// 调用后端API解散班级
				console.log('准备调用解散班级API:',
					`http://localhost:8088/class/dissolve?classCode=${classInfo.value.classCode}`);
				console.log('当前班级信息:', classInfo.value);
				console.log('Authorization Token:', localStorage.getItem('token') || '未找到token');
				console.log('使用的API实例:', classApi);

				const response = await classApi.delete('/class/dissolve', {
					params: {
						classCode: classInfo.value.classCode
					},
					headers: {
						'Authorization': localStorage.getItem('token') || ''
					}
				})

				console.log('解散班级API响应:', response);
				if (response && response.data && response.data.code === 200) {
					ElMessage.success(response.data.data || '班级解散成功')
					// 解散成功后返回班级列表
					setTimeout(() => {
						router.push('/classes')
					}, 1500)
				} else {
					ElMessage.error(response?.data?.message || '班级解散失败')
				}
			} catch (error) {
				console.error('解散班级失败:', error)
				ElMessage.error(`解散班级失败: ${error.response?.data?.message || '请检查后端服务是否运行或权限是否足够'}`)
			} finally {
				loading.close()
			}
		}
	}



	// 获取课程数据 - 简化处理逻辑，确保能显示数据
	const fetchCurriculum = async () => {
		const loading = ElLoading.service({
			lock: true,
			text: '加载课程信息中...',
			background: 'rgba(255, 255, 255, 0.7)'
		});

		try {
			// 调用新的后端API获取课程数据
			console.log(`请求课程数据: /schedule/getClassSchedule/${classId.value}`);
			const response = await axios.get(`http://localhost:9002/schedule/getClassSchedule/${classId.value}`);

			if (response.data && response.data.success) {
				// 后端返回的是数组直接使用
				curriculumList.value = Array.isArray(response.data.data) ? response.data.data : [];
				courseCount.value = curriculumList.value.length;
				console.log('获取到的课程数据:', curriculumList.value);

				// 显示获取到的课程数量
				ElMessage.success(`成功加载 ${courseCount.value} 门课程`);
			} else {
				curriculumList.value = [];
				courseCount.value = 0;
				ElMessage.warning('未获取到课程数据');
			}

		} catch (error) {
			console.error('获取课程数据失败:', error);
			ElMessage.error(`获取课程失败: ${error.message || '请检查后端服务是否运行'}`);
			curriculumList.value = [];
			courseCount.value = 0;
		} finally {
			loading.close();
		}
	};

	// 打开新建课程弹窗
	const handleAddCourse = () => {
		isEditMode.value = false
		// 重置表单
		Object.keys(courseForm).forEach(key => {
			courseForm[key] = ''
		})
		// 默认填充班级ID
		courseForm.classId = classId.value.toString()
		dialogVisible.value = true
	}

	// 打开编辑课程弹窗
	const handleEditCourse = (course, weekday, times) => {
		isEditMode.value = true
		// 填充表单数据
		courseForm.id = course.id
		courseForm.times = times
		courseForm.classTimeOn = course.classTimeOn
		courseForm.classTimeEnd = course.classTimeEnd
		courseForm.classId = course.classId.toString()
		courseForm.course = course.course
		courseForm.lecturer = course.lecturer
		courseForm.dateDay = course.dateDay.toString()
		courseForm.classRoom = course.room
		dialogVisible.value = true
		courseForm.date = weekday
	}

	// 关闭弹窗
	const handleClose = () => {
		dialogVisible.value = false
		if (courseFormRef.value) {
			courseFormRef.value.resetFields()
		}
	}

	// 提交表单
	const submitForm = async () => {
		if (!courseFormRef.value) return

		try {
			await courseFormRef.value.validate()

			// 准备提交的数据
			const submitData = {
				...courseForm
			}
			// 转换数字类型
			submitData.classId = Number(submitData.classId)
			submitData.dateDay = Number(submitData.dateDay)

			const loading = ElLoading.service({
				lock: true,
				text: isEditMode.value ? '正在更新课程...' : '正在创建课程...',
				background: 'rgba(255, 255, 255, 0.7)'
			})

			try {
				if (isEditMode.value) {
					// 调用更新接口
					await courseApi.post('/course/update', submitData)
					ElMessage.success('课程更新成功')
				} else {
					// 调用新增接口
					await courseApi.post('/course/add', submitData)
					ElMessage.success('课程创建成功')
				}

				// 关闭弹窗
				dialogVisible.value = false
				// 重新加载课程数据
				fetchCurriculum()
			} catch (error) {
				console.error(isEditMode.value ? '更新课程失败' : '创建课程失败', error)
				ElMessage.error(
					`${isEditMode.value ? '更新课程' : '创建课程'}失败: ${error.response?.data?.message || error.message}`
				)
			} finally {
				loading.close()
			}
		} catch (error) {
			console.error('表单验证失败', error)
			return false
		}
	}

	onMounted(() => {
		// 刷新学生列表到sessionStorage
		refreshStudentList()
		updateTime();
		setInterval(updateTime, 1000);
		fetchCurriculum(); // 加载课程数据
	})

	// 监听班级ID变化，重新加载课程
	watch(classId, () => {
		fetchCurriculum();
	})
</script>

<style scoped>
	@keyframes blob {
		0% {
			transform: translate(0px, 0px) scale(1);
		}

		33% {
			transform: translate(30px, -50px) scale(1.1);
		}

		66% {
			transform: translate(-20px, 20px) scale(0.9);
		}

		100% {
			transform: translate(0px, 0px) scale(1);
		}
	}

	.animate-blob {
		animation: blob 7s infinite;
	}

	.animation-delay-2000 {
		animation-delay: 2s;
	}

	.animation-delay-4000 {
		animation-delay: 4s;
	}

	/* DNA 双螺旋动画 */
	.helix-container {
		position: relative;
		width: 220px;
		height: 180px;
		perspective: 600px;
		transform-style: preserve-3d;
	}

	.helix-row {
		position: relative;
		width: 100%;
		height: 18px;
		display: flex;
		align-items: center;
		justify-content: center;
		animation: helix-rise 4s linear infinite;
		animation-delay: calc(var(--i) * -0.2s);
	}

	.helix-dot {
		width: 12px;
		height: 12px;
		border-radius: 9999px;
		display: inline-block;
	}

	.helix-dot.left {
		background: radial-gradient(circle at 30% 30%, #60a5fa, #2563eb);
		transform: translateX(-70px) translateZ(-20px);
		box-shadow: 0 6px 16px rgba(37, 99, 235, 0.35);
	}

	.helix-dot.right {
		background: radial-gradient(circle at 30% 30%, #34d399, #059669);
		transform: translateX(70px) translateZ(20px);
		box-shadow: 0 6px 16px rgba(5, 150, 105, 0.35);
	}

	@keyframes helix-rise {
		0% {
			transform: translateY(120px) rotateY(0deg);
		}

		50% {
			transform: translateY(60px) rotateY(180deg);
		}

		100% {
			transform: translateY(0) rotateY(360deg);
		}
	}
</style>